﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using QBZ.Evaluation.Domains;
using QBZ.Evaluation.Domains.OAuth;
using QBZ.Evaluation.Domains.Permissions;
using QBZ.Evaluation.Models;
using QBZ.Evaluation.Views.Middleware;
using System;
using System.Text;

namespace QBZ.Evaluation.Views
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMemoryCache();
            //services.Configure<CookiePolicyOptions>(options =>
            //{
            //    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            //    options.CheckConsentNeeded = context => true;
            //    options.MinimumSameSitePolicy = SameSiteMode.None;
            //});
            //services.AddSingleton<InitAllDI>();//AddSingleton
            services.AddSingleton<UserDomain>();//AddSingleton
            services.AddSingleton<RoleDomain>();//AddSingleton
                                                /*services.AddDistributedMemoryCache();//启用session之前必须先添加内存
                                                services.AddSession(options =>
                                                {
                                                    options.Cookie.Name = ".AdventureWorks.Session";
                                                    //options.IdleTimeout = TimeSpan.FromSeconds(10);//设置session的过期时间
                                                    options.Cookie.HttpOnly = true;//设置在浏览器不能通过js获得该cookie的值
                                                }
                                                );*/
                                                //services.AddAuthentication(options =>
                                                //{
                                                //    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                                                //})
                                                //.AddCookie();
            services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));

            // assign JwtSettings model
            var jwtSettings = new JwtSettings();
            Configuration.Bind("JwtSettings", jwtSettings);
            services.AddAuthentication(options =>
            {
                //Auth middleware config
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                // set jwt token parameters
                o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidIssuer = jwtSettings.Issuer,//Issuer
                    ValidAudience = jwtSettings.Audience,//Audience
                    //Encryption secret key
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey)),
                    ValidateIssuer = true, //whether or not valid Issuer
                    ValidateAudience = true, //whether or not valid Audience
                    ValidateLifetime = true, //whether or not valid out-of-service time
                    ValidateIssuerSigningKey = true, //whether or not valid SecurityKey　　　　　　　　　　　
                    ClockSkew = TimeSpan.Zero//Allowed server time offset
                };
            });
            services.AddCors();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //services.AddSingleton<UserStore>();
            services.AddSingleton<DocumentStore>();
            //services.AddSingleton<IAuthorizationHandler, DocumentAuthorizationHandler>();
            services.AddSingleton<IAuthorizationHandler, PermissionAuthorizationHandler>();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            //app.UseHttpsRedirection();
            app.UseDefaultFiles();
            app.UseStaticFiles();
            //app.UseCookiePolicy();
            //app.UseSession();
            app.UseCors(builder => builder.WithOrigins("*"));
            var Credentials = Configuration.GetSection("Credentials").Get<CredentialsSetting>();
            LoginProvider.UseQQ(Credentials.QQ.client_id, Credentials.QQ.client_secret);
            LoginProvider.UseWechat(Credentials.Wechat.client_id, Credentials.Wechat.client_secret);
            LoginProvider.UseWeibo(Credentials.Weibo.client_id, Credentials.Weibo.client_secret);
            app.UseErrorHandling();

            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "api/{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
